# -*- coding: utf-8 -*-
import wx
import time, threading
import serial
import numpy
from json_read4 import get_distance
from json_read4 import rssi_group_size
from json_read4 import location_init
from json_read4 import location_measure
from json_read4 import get_route_order
import json_read4

global ser
from queue import Queue
from queue import Empty as QueueEmptyException
import sys
import socket
import pickle

ser = serial.Serial()
ser.bandrate = 115200
ser.port = 'COM11'
ser.timeout = 5
global isThreadRun
isThreadRun = True
global rssi_sample
rssi_sample = Queue(maxsize=100)
global rssi_sample2
rssi_sample2 = Queue(maxsize=100)
global rssi_sample3
rssi_sample3 = Queue(maxsize=100)


class MyFrame(wx.Frame):
    '''
    自定义窗口
    '''

    def link_click(self, event):
        print(event.GetId())
        if ser.isOpen():
            ser.write([0x01, 0x01])
            if event.GetId() == -31995:
                ser.write([0x1B, 0xF3, 0xEE, 0x7F, 0x93, 0xF0])
            if event.GetId() == -31994:
                ser.write([0xE8, 0x14, 0xE2, 0x9A, 0x63, 0xEF])
            if event.GetId() == -31993:
                ser.write([0x05, 0x9D, 0x2E, 0xBA, 0x3C, 0xC1])
            ser.write([0x0d, 0x0a])

    def click(self, event):
        global isThreadRun
        isThreadRun = False
        print('quit')
        if event == wx.EVT_BUTTON:
            self.Close()
        sys.exit()

    def begin_click(self, event):
        global ser
        if self.button.GetLabel() == u"开始":
            try:
                ser = serial.Serial('COM11', 115200, timeout=5)
                self.button.SetLabel(u"停止")
            except serial.SerialException as err:
                print(err.message)
                dlg = wx.MessageDialog(None, err.message, u"提示", wx.OK | wx.ICON_ERROR)
                dlg.ShowModal()
        else:
            try:
                ser.close()
                self.button.SetLabel(u"开始")
            except serial.SerialException as err:
                print(err.message)
                dlg = wx.MessageDialog(None, err.message, u"提示", wx.OK | wx.ICON_ERROR)
                dlg.ShowModal()

    def reset_click(self, event):
        global rssi_num
        del rssi_num[0][:]
        del rssi_num[1][:]
        del rssi_num[2][:]
        self.txt3.SetLabel(u"已复位")

    def add_link_button(self, panel, sizer):
        size = wx.BoxSizer(wx.HORIZONTAL)
        link_button1 = wx.Button(panel, -1, u"连接蓝牙路由1(0E)")
        size.Add(link_button1, 0, wx.TOP | wx.LEFT, 2)
        link_button2 = wx.Button(panel, -1, u"连接蓝牙路由2(FC)")
        size.Add(link_button2, 0, wx.TOP | wx.LEFT, 2)
        link_button3 = wx.Button(panel, -1, u"连接蓝牙路由3(A2)")
        size.Add(link_button3, 0, wx.TOP | wx.LEFT, 2)
        sizer.Add(size, 0, wx.TOP, 2)
        self.Bind(wx.EVT_BUTTON, self.link_click, link_button1, 1, -1)
        self.Bind(wx.EVT_BUTTON, self.link_click, link_button2, 2, -1)
        self.Bind(wx.EVT_BUTTON, self.link_click, link_button3, 3, -1)

    def __init__(self, parent):
        wx.Frame.__init__(self, parent, -1, u'RSSI测距', size=(600, 300))
        panel = wx.Panel(self)
        size = wx.BoxSizer(wx.VERTICAL)
        panel.SetSizer(size)

        self.txt = wx.StaticText(panel, -1, u'坐标位置：\n\n\n')
        size.Add(self.txt, 0, wx.TOP | wx.LEFT, 2)
        self.txt2 = wx.StaticText(panel, -1, u'信号采集信息：\n\n\n')
        size.Add(self.txt2, 0, wx.TOP | wx.LEFT, 2)
        self.txt3 = wx.StaticText(panel, -1, u'提示信息')
        self.txt3.SetBackgroundColour(wx.Colour(255, 255, 0))
        size.Add(self.txt3, 0, wx.TOP | wx.LEFT, 2)

        self.add_link_button(panel, size)

        size2 = wx.BoxSizer(wx.HORIZONTAL)
        self.button = wx.Button(panel, -1, u"开始")
        size2.Add(self.button, 0, wx.BOTTOM | wx.LEFT, 2)

        button2 = wx.Button(panel, -1, u"复位")
        size2.Add(button2, 0, wx.BOTTOM | wx.LEFT, 2)

        exit_button = wx.Button(panel, -1, u"退出")
        size2.Add(exit_button, 0, wx.BOTTOM | wx.LEFT, 2)

        size.Add(size2, 0, wx.TOP, 2)
        self.Bind(wx.EVT_BUTTON, self.click, exit_button, -1, -1)
        self.Bind(wx.EVT_BUTTON, self.begin_click, self.button, -1, -1)
        self.Bind(wx.EVT_BUTTON, self.reset_click, button2, -1, -1)
        self.Bind(wx.EVT_CLOSE, self.click)
        self.Centre()

    def SetText(self, txt):
        self.txt.SetLabel(txt)


class MyApp(wx.App):
    def OnInit(self):
        self.frame = MyFrame(None)
        self.frame.Show(True)
        print('init--', self.frame.GetId())
        return True


app = MyApp()


# 新线程执行的代码:
def loop():
    print('thread %s is running...' % threading.current_thread().name)
    global rssi_info
    rssi_info = [0x0E, 0, 0xFC, 0, 0xA2, 0]
    while isThreadRun:
        if ser.isOpen() == False:
            time.sleep(1)
            continue
        try:
            ser_data = ser.read(2)
        except:
            pass
        if len(ser_data) == 2:
            rssi = ser_data[1] - 256
            if rssi_info[0] == ser_data[0]:
                rssi_info[1] = rssi
                rssi_sample.put(rssi)
            elif rssi_info[2] == ser_data[0]:
                rssi_info[3] = rssi
                rssi_sample2.put(rssi)
            elif rssi_info[4] == ser_data[0]:
                rssi_info[5] = rssi
                rssi_sample3.put(rssi)
        else:
            print('no received')
    if ser.isOpen():
        ser.close()
    print('thread %s is stop...' % threading.current_thread().name)


def socket_link():
    while isThreadRun:
        try:
            HOST = '127.0.0.1'
            PORT = 8888
            s = socket.socket()
            s.bind((HOST, PORT))
            s.listen(1)
            return s.accept()
            break
        except BaseException as e:
            print("socket:" + str(e))
        time.sleep(1)


def loop2():
    print('thread %s is running...' % threading.current_thread().name)
    # import os
    # print(os.system('C:\\Users\\panpan\\Anaconda2\\envs\\CNN_Test\\python ' + 'opencv_test.py'))
    location_init([[0.0, 2.80], [6.70, 2.80], [3.20, 0]])
    print(json_read4.route_list)
    global rssi_num
    rssi_num = [[], [], []]
    conn = None
    conn, addr = socket_link()
    distance_num = [-1] * 3
    route_near_index = -1
    while isThreadRun:
        while True:
            try:
                rssi_num[0].append(rssi_sample.get(block=False, timeout=0.5))
                if len(rssi_num[0]) > rssi_group_size:
                    del rssi_num[0][0]
                    # del rssi_num[1][:]
                    # del rssi_num[2][:]
            except QueueEmptyException:
                break
        while True:
            try:
                rssi_num[1].append(rssi_sample2.get(block=False, timeout=0.5))
                if len(rssi_num[1]) > rssi_group_size:
                    # del rssi_num[0][:]
                    del rssi_num[1][0]
                    # del rssi_num[2][:]
            except QueueEmptyException:
                break
        while True:
            try:
                rssi_num[2].append(rssi_sample3.get(block=False, timeout=0.5))
                if len(rssi_num[2]) > rssi_group_size:
                    # del rssi_num[0][:]
                    # del rssi_num[1][:]
                    del rssi_num[2][0]
            except QueueEmptyException:
                break
        if isThreadRun:
            # print rssi_sample2
            if len(rssi_num[0]) == rssi_group_size:
                distance_num[0] = json_read4.route_list[0][2]
            if len(rssi_num[1]) == rssi_group_size:
                distance_num[1] = json_read4.route_list[1][2]
            if len(rssi_num[2]) == rssi_group_size:
                distance_num[2] = json_read4.route_list[2][2]
            measure_result = location_measure(rssi_num)
            location_result = measure_result
            if len(rssi_num[0]) > rssi_group_size / 2 or \
                    len(rssi_num[1]) > rssi_group_size / 2 or \
                    len(rssi_num[2]) > rssi_group_size / 2:
                route_near_index = get_route_order(rssi_num)
            if location_result is not None and conn is not None:
                try:
                    conn.sendall(
                        pickle.dumps(([location_result[0][2],
                                       location_result[1][2],
                                       location_result[2][2]],
                                      rssi_num, route_near_index)))
                except:
                    conn, addr = socket_link()
            txt = u'坐标位置：%s' % str(location_result)
            txt += '\n'
            txt += u'最近的路由器序号：%s' % route_near_index
            txt += '\n'
            txt += ''
            app.frame.txt.SetLabel(txt)
            txt = u'信号采集信息：%s\n' % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            txt += u'%02X:%+3d dBm 采集数量：%04d 距离：%s' % (rssi_info[0], rssi_info[1],
                                                       len(rssi_num[0]), distance_num[0])
            txt += '\n'
            txt += u'%02X:%+3d dBm 采集数量：%04d 距离：%s' % (rssi_info[2], rssi_info[3],
                                                       len(rssi_num[1]), distance_num[1])
            txt += '\n'
            txt += u'%02X:%+3d dBm 采集数量：%04d 距离：%s' % (rssi_info[4], rssi_info[5],
                                                       len(rssi_num[2]), distance_num[2])
            app.frame.txt2.SetLabel(txt)
            # print 'id=%02X,rssi=%d' % (ord(ser_data[0]),rssi)
        else:
            pass
        # print('UI Run')
        time.sleep(1)
    print('thread %s is stop...' % threading.current_thread().name)


# def socket_loop():
#     while isThreadRun:
#         try:
#             HOST = '127.0.0.1'
#             PORT = 8888
#             s = socket.socket()
#             s.bind((HOST, PORT))
#             s.listen(1)
#             conn, addr = s.accept()
#             break
#         except BaseException as e:
#             print("socket:" + str(e))
#         time.sleep(1)
#     send_data = [7, 8]
#     while isThreadRun:
#         send_data[1] += 1
#         send_data[1] %= 10
#         # s.sendall(7, 8)
#         conn.sendall(bytes(send_data))
#         time.sleep(0.5)
#     conn.close()
#     s.close()


t = threading.Thread(target=loop, name='LoopThread')
t.start()
t = threading.Thread(target=loop2, name='UIThread')
t.start()


# t = threading.Thread(target=socket_loop, name='socket_loop')
# t.start()

def open_opencv_test():
    import os
    print(os.system('C:\\Users\\panpan\\Anaconda2\\envs\\CNN_Test\\python ' + 'opencv_test.py'))


t = threading.Thread(target=open_opencv_test, name='UIThread')
t.start()
if __name__ == '__main__':
    # os.chdir('C:\\Users\\panpan\\Anaconda2\\envs\\CNN_Test')
    app.MainLoop()
